//axios 封装
import axios from 'axios';
import QS from 'qs';
// import router from '../router'
// import store from '../store'
import { ElMessage,ElNotification } from 'element-plus'
// import pinia from '@/store/wmsGlobal'
import { useWmsGlobal } from '@/store/wmsGlobal'
import NProgress from 'nprogress';
import pinia from '@/store/asPinia';
const wmsGlobal = useWmsGlobal(pinia)
// axios.defaults.withCredentials = true;
// console.log(axios.defaults);
axios.defaults.baseURL = '/wms'
axios.defaults.timeout = 10000;
axios.interceptors.request.use(config => {
  NProgress.start();
  return config;
}, error => {
  ElMessage.error('请求超时');
  NProgress.done();
  return Promise.reject(error)
})
axios.interceptors.response.use(config => {
  NProgress.done();
  if (config.data.code != 200) {
    if (config.data.code == -999) {
      window.sessionStorage.clear(); //清空sessionstorage
      window.location.reload()
    } if (config.data.code == -201) {
      wmsGlobal.isLogin=false;
    }else if (config.data.status) {
      if (config.data.status !== "ok") {
        ElMessage.Message({
          showClose: true,
          message: config.data.code +" "+config.data.data,
          type: 'error'
        })
      }
      
    } else {
      if(!config.data.code){
        wmsGlobal.isLogin = false;
      }else{
        ElNotification({ title: 'Error', message:config.data.message, type: 'error' })
      }
    }
  }
  return config;
})
export function getCookie(name) {
  let value = "";
  let cookies = document.cookie.split("; ");
  for (let i = 0; i < cookies.length; i++) {
    let arr = cookies[i].split("=");
    if (arr[0] === name) {
      value = arr[1];
    }
  }
  return value;
}
const e_id = getCookie("account");
function isError(data){
  if(!data || data === ""){
    return []
  }
  // if(data.message === '成功'){
  //   data.code = 1;
  // }
  return data
}
function formatNull(params){
  if(!params)return
  if(Object.keys(params).length === 0 )return params
  params.man = e_id;

  if(Array.isArray(params)){
    params.forEach((item)=>{
      if(item != null && typeof item === 'object'){
        formatNull(item)
      }else{
        if(item === ""){
          item = null;
        }
      }
    })
  }else if(Object.prototype.toString(params) ==='[object Object]'){
    for (const key in params) {
      if(Array.isArray(params[key])){
        formatNull(params[key])
      }
      if(params[key] === ""){
        params[key] = null;
      }
    }
    
  }
}

function serviceAdapter(val){return val}
/**
 * get方法，对应get请求GET 
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function GET(url, params) {
  url = serviceAdapter(url);
  formatNull(params);
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      paramsSerializer: function (params) {
        return QS.stringify(params, {
          arrayFormat: 'repeat'
        })
      }
    }, ).then(res => {
      resolve(isError(res.data));
    }).catch(err => {
      reject(err.data)
    })
  });
}
export function GETRESET(url, params) {
  url = serviceAdapter(url);
  formatNull(params);
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      paramsSerializer: function (params) {
        return QS.stringify(params, {
          arrayFormat: 'repeat'
        })
      }
    }, ).then(res => {
      resolve(isError(res.data));
    }).catch(err => {
      reject(err.data)
    })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function POST(url, params) {
  url = serviceAdapter(url);
  formatNull(params);
  return new Promise((resolve, reject) => {
    axios.post(url, QS.stringify(params, {
        arrayFormat: 'repeat'
      }))
      .then(res => {
        resolve(isError(res.data));
      })
      .catch(err => {
        reject(err.data)
      })
  });
}

/**
 * postJson方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function POSTJSON(url, params) {
  url = serviceAdapter(url);
  formatNull(params);
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        resolve(isError(res.data));
      })
      .catch(err => {
        reject(err.data)
      })
  });
}


export default {GET,POST,GETRESET,POSTJSON}